package com.choosefine.paycenter.common.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.io.*;
import java.util.Map;
import java.util.Set;

/**
 * Comments：
 * Author：Jay Chang
 * Create Date：2017/3/14
 * Modified By：
 * Modified Date：
 * Why & What is modified：
 * Version：v1.0
 */
@Slf4j
public class RequestUtils {

    private static RequestUtils instance;

    private static HttpClient httpClient;

    static {
        httpClient = new HttpClient();
    }

    private RequestUtils(){}

    public static synchronized RequestUtils getInstance(){
        return null != instance ? instance : (instance = new RequestUtils());
    }

    public JSONObject getForString(RestTemplate restTemplate,String url, Map<String,Object> params){
        ResponseEntity<JSONObject> responseEntity = restTemplate.getForEntity(url,JSONObject.class,params);
        return responseEntity.getBody();
    }

    public JSONObject postForString(RestTemplate restTemplate,String url,Map<String,Object> params){
        JSONObject jsonObject = new JSONObject();
        for(Map.Entry<String,Object> entry : params.entrySet()){
            jsonObject.put(entry.getKey(),entry.getValue());
        }
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url,jsonObject,JSONObject.class);
        return responseEntity.getBody();
    }

    public String postForString(String url,Map<String,String> params){
        return postForString(url,params,"GBK");
    }

    public String postForString(String url,Map<String,String> params,String encoding){
        PostMethod postMethod = null;
        try {
            postMethod = new PostMethod(url);
            Set<Map.Entry<String,String>> entrySet = null;
            if(null != params && CollectionUtils.isNotEmpty(entrySet = params.entrySet())){
                for(Map.Entry<String,String> entry : entrySet){
                    postMethod.addParameter(entry.getKey(), entry.getValue());
                }
            }
            httpClient.executeMethod(postMethod);
            return new String(postMethod.getResponseBody(),encoding);
        }catch (IOException e){
            throw new RuntimeException(e);
        }finally {
            if(null != postMethod) {
                postMethod.releaseConnection();
            }
        }
    }
}
